//
//  BMPhotoIOAuthTool.m
//  bigmama
//
//  Created by huyuchen on 2017/9/28.
//  Copyright © 2017年 盛成文化. All rights reserved.
//

#import "BMPhotoIOAuthTool.h"

@implementation BMPhotoIOAuthTool

// 请求相片授权
+ (void)requestAuthForPhotoWithAuthedStatus:(void(^)(PHAuthorizationStatus status))authedBlock denied:(void(^)(PHAuthorizationStatus status))deniedBlock
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        switch (status) {
            case PHAuthorizationStatusAuthorized:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (authedBlock) {
                        authedBlock(status);
                    }
                });
                break;
            }
            default:
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (deniedBlock) {
                        deniedBlock(status);
                    }
                });
                break;
            }
        }
    }];
}

+ (void)checkAuthForPhotoWithAuthedStatus:(void(^)(PHAuthorizationStatus status))authedBlock denied:(void(^)(PHAuthorizationStatus status))deniedBlock noRequest:(void(^)(PHAuthorizationStatus status))noRequestBlock
{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    switch (status)
    {
        case PHAuthorizationStatusNotDetermined:
            if (noRequestBlock) {
                noRequestBlock(status);
            }
            break;
        case PHAuthorizationStatusRestricted:
        case PHAuthorizationStatusDenied:
        {
            if (deniedBlock) {
                deniedBlock(status);
            }
            break;
        }
        case PHAuthorizationStatusAuthorized:
        default:
        {
            if (authedBlock) {
                authedBlock(status);
            }
            break;
        }
    }
}

+ (BOOL)checkCameraAuth {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
        authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
    {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"需要开启相机权限才能拍摄照片哦" cancelButtonTitle:@"取消" otherButtonTitles:@[@"去开启"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                if (IOS8) {
                    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
                        [[UIApplication sharedApplication] openURL:settingURL];
                    }
                }
            }
        }];
        return NO;
    }
    return YES;
}
@end
